// 事件处理
import React from 'react'

const messages = ['React','Vue','Angular'];

//登陆or退出 按钮
function LogButton(props) {
    return (
        <button onClick={props.onClick}>{props.btnText}</button>
    )
}

function UserGreeting() {
    return <h1>Welcome admin.</h1>
}
function GuestGreeting() {
    return <h1>Please sign up.</h1>
}
function WarningTip(props) {
    if (!props.warning){
        return null
    }

    return (
        <div><mark>Warning!</mark></div>
    )
}

function MailBox(props) {
    const unreadMsgLen = props.message.length;
    return (
        <div>
            {
                unreadMsgLen>0&&<h4>You have {unreadMsgLen} unread messages.</h4>
            }
        </div>
    )
}

//根据登陆状态判断问候语
function Greeting(props) {
    if (props.isLogIn){
        return <UserGreeting/>
    } else{
        return <GuestGreeting/>
    }
}

class Toggle extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isToggleOn:true,
            isLogIn:false,
            warning:true,
        };
        this.handleClick = this.handleClick.bind(this);
        this.bindLogin = this.bindLogin.bind(this);
        this.bindLogout = this.bindLogout.bind(this);
    }

    handleClick(){
        // this.setState(function(prevState){
        //     return {
        //         isToggleOn:!prevState.isToggleOn
        //     }
        // })
        this.setState(prevState=>({
            isToggleOn:!prevState.isToggleOn
        }))
    }

    //属性初始化器语法：箭头函数，在创建函数时自动绑定this
    handleClick2=(name,e)=>{
        console.log('Just Click',name)
    }

    //登陆
    bindLogin(){
        this.setState({isLogIn:true,warning:false})
    }

    //退出
    bindLogout(){
        this.setState({isLogIn:false,warning:true})
    }


    render(){
        const isLogIn = this.state.isLogIn;
        let button;//使用变量来储存元素
        if(isLogIn){
            button = <LogButton onClick={this.bindLogout} btnText="Log out"/>
        }else{
            button = <LogButton onClick={this.bindLogin} btnText="Log in"/>
        }
        return (
            <div>
                <MailBox message={messages}/>
                <Greeting isLogIn={isLogIn}/>
                <WarningTip warning={this.state.warning}/>
                {button}
                <button onClick={this.handleClick}>{this.state.isToggleOn?'ON':'OFF'}</button>
                <button onClick={(e)=>this.handleClick2('Lucia Way1',e)}>Pass param Way1</button>
                <button onClick={this.handleClick2.bind(this,'Lucia Way2')}>Pass param Way2</button>
            </div>
        )
    }
}

export default Toggle;